<!--
 * @Author: your name
 * @Date: 2020-06-23 15:36:51
 * @LastEditTime: 2020-06-23 17:14:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-next-test\src\views\TestVuex.vue
--> 
<template>
  <div>
    <div>简单事件例子：</div>
    <p>{{count}}</p>
    <button @click="countAdd">点击加一</button>

    <h2>vuex简单例子</h2>
    <p>test.a:{{doubleCount}}</p>
    <button @click="update">初始化状态</button>
  </div>
</template>

<script>
import {
  ref,
  watch,
  getCurrentInstance,
  computed,
   /*mounted,reactive,toRef*/
} from "vue";

function userCountAdd() {
  const count = ref(0);

  const countAdd = () => {
    count.value++;
  };

  const { ctx } = getCurrentInstance();
  const doubleCount= computed(() =>ctx.$store.state.test.a);
  console.log(count.value);



  watch(
    () => count.value,
    value => {
      console.log("newVal:", value);
      update(value)
    }
  );

  

  const update = function(val) {
    console.log("update state");
    let temp = val&&typeof val=='number'&&val||0;
    ctx.$store.commit("SetTestA", temp);
    !temp?count.value = temp:null;
  };
  return {
    count,
    countAdd,
    update,
    doubleCount
  };
}

export default {
  setup() {
    const { count, countAdd, update,doubleCount } = userCountAdd();
    return {
      count,
      countAdd,
      update,
      doubleCount
    };
  }
};
</script>